{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Python正则表达式"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "正则表达式是处理字符串的强大工具，拥有独特的语法和独立的处理引擎。<br>\n",
    "<br>\n",
    "我们在大文本中匹配字符串时，有些情况用str自带的函数(比如find, in)可能可以完成，有些情况会稍稍复杂一些(比如说找出所有“像邮箱”的字符串，所有和abc相关的句子)，这个时候我们需要一个某种模式的工具，这个时候正则表达式就派上用场了。<br>\n",
    "<br>\n",
    "说起来正则表达式效率上可能不如str自带的方法，但匹配功能实在强大太多。对啦，正则表达式不是Python独有的，如果已经在其他语言里使用过正则表达式，这里的说明只需要简单看一看就可以上手啦。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.语法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "下面是一张有些同学比较熟的图，我们俗称python正则表达式小抄，把写正则表达式当做一个开卷考试，显然容易得多。<br>\n",
    "当你要匹配 一个/多个/任意个 数字/字母/非数字/非字母/某几个字符/任意字符，想要 贪婪/非贪婪 匹配，想要捕获匹配出来的 第一个/所有 内容的时候，记得这里有个小手册供你参考。<br>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.验证工具"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们最喜爱的正则表达式在线验证工具之一是[http://regexr.com/](http://regexr.com/)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.挑战与提升"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "长期做自然语言处理的同学正则表达式都非常熟，曾经有半年写了大量的正则表达式，以至于同事间开玩笑说，只要是符合某种规律或者模式的串，肯定分分钟能匹配出来。<br>\n",
    "对于想练习正则表达式，或者短期内快速get复杂技能，or想挑战更复杂的正则表达式的同学们。 请戳[https://alf.nu/RegexGolf](https://alf.nu/RegexGolf)<br> \n",
    "正则表达式进阶练习 so, 各位宝宝enjoy yourself"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.Python案例"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### re模块"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python通过re模块提供对正则表达式的支持。\n",
    "使用re的一般步骤是\n",
    "\n",
    "> 1.将正则表达式的字符串形式编译为Pattern实例 <br>\n",
    "> 2.使用Pattern实例处理文本并获得匹配结果（一个Match实例）<br>\n",
    "> 3.使用Match实例获得信息，进行其他的操作。<br>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello, world!\n"
     ]
    }
   ],
   "source": [
    "# encoding: UTF-8\n",
    "import re\n",
    "\n",
    "# 将正则表达式编译成Pattern对象\n",
    "pattern = re.compile(r'hello.*\\!')\n",
    "\n",
    "# 使用Pattern匹配文本，获得匹配结果，无法匹配时将返回None\n",
    "match = pattern.match('hello, world! How are you?')\n",
    "\n",
    "if match:\n",
    "    # 使用Match获得分组信息\n",
    "    print match.group()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### re.compile(strPattern[, flag]):"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这个方法是Pattern类的工厂方法，用于将字符串形式的正则表达式编译为Pattern对象。<br>\n",
    "第二个参数flag是匹配模式，取值可以使用按位或运算符'|'表示同时生效，比如re.I | re.M。<br>\n",
    "当然，你也可以在regex字符串中指定模式，比如re.compile('pattern', re.I | re.M)等价于re.compile('(?im)pattern')<br>\n",
    "flag可选值有：<br>\n",
    "re.I(re.IGNORECASE): 忽略大小写（括号内是完整写法，下同）<br>\n",
    "re.M(MULTILINE): 多行模式，改变'^'和'$'的行为（参见上图）<br>\n",
    "re.S(DOTALL): 点任意匹配模式，改变'.'的行为<br>\n",
    "re.L(LOCALE): 使预定字符类 \\w \\W \\b \\B \\s \\S 取决于当前区域设定<br>\n",
    "re.U(UNICODE): 使预定字符类 \\w \\W \\b \\B \\s \\S \\d \\D 取决于unicode定义的字符属性<br>\n",
    "re.X(VERBOSE): 详细模式。这个模式下正则表达式可以是多行，忽略空白字符，并可以加入注释。以下两个正则表达式是等价的：<br>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "regex_1 = re.compile(r\"\"\"\\d +  # 数字部分\n",
    "                         \\.    # 小数点部分\n",
    "                         \\d *  # 小数的数字部分\n",
    "                        \"\"\")\n",
    "regex_2 = re.compile(r\"\\d+\\.\\d*\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Match"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Match对象是一次匹配的结果，包含了很多关于此次匹配的信息，可以使用Match提供的可读属性或方法来获取这些信息。<br>\n",
    "match属性：<br>\n",
    " string: 匹配时使用的文本。<br>\n",
    " re: 匹配时使用的Pattern对象。<br>\n",
    " pos: 文本中正则表达式开始搜索的索引。值与Pattern.match()和Pattern.seach()方法的同名参数相同。<br>\n",
    " endpos: 文本中正则表达式结束搜索的索引。值与Pattern.match()和Pattern.seach()方法的同名参数相同。<br>\n",
    " lastindex: 最后一个被捕获的分组在文本中的索引。如果没有被捕获的分组，将为None。<br>\n",
    " lastgroup: 最后一个被捕获的分组的别名。如果这个分组没有别名或者没有被捕获的分组，将为None。<br>\n",
    "方法：<br>\n",
    " group([group1, …]):<br> \n",
    " 获得一个或多个分组截获的字符串；指定多个参数时将以元组形式返回。group1可以使用编号也可以使用别名；编号0代表整个匹配的子串；不填写参数时，返回group(0)；没有截获字符串的组返回None；截获了多次的组返回最后一次截获的子串。<br>\n",
    " groups([default]): <br>\n",
    " 以元组形式返回全部分组截获的字符串。相当于调用group(1,2,…last)。default表示没有截获字符串的组以这个值替代，默认为None。<br>\n",
    " groupdict([default]): <br>\n",
    " 返回以有别名的组的别名为键、以该组截获的子串为值的字典，没有别名的组不包含在内。default含义同上。<br>\n",
    " start([group]): <br>\n",
    " 返回指定的组截获的子串在string中的起始索引（子串第一个字符的索引）。group默认值为0。<br>\n",
    " end([group]): <br>\n",
    " 返回指定的组截获的子串在string中的结束索引（子串最后一个字符的索引+1）。group默认值为0。<br>\n",
    " span([group]): <br>\n",
    " 返回(start(group), end(group))。<br>\n",
    " expand(template): <br>\n",
    " 将匹配到的分组代入template中然后返回。template中可以使用\\id或\\g、\\g引用分组，但不能使用编号0。\\id与\\g是等价的；但\\10将被认为是第10个分组，如果你想表达\\1之后是字符'0'，只能使用\\g<1>0。<br>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "m.string: hello wodeshijie!\n",
      "m.re: <_sre.SRE_Pattern object at 0x0000000004DFB030>\n",
      "m.pos 0\n",
      "m.endpos: 17\n",
      "m.lastindex: 3\n",
      "m.lastgroup: sign\n",
      "m.group(1,2): ('hello', 'wodeshijie')\n",
      "m.groups(): ('hello', 'wodeshijie', '!')\n",
      "m.groupdict(): {'sign': '!'}\n",
      "m.start(2): 6\n",
      "m.end(2): 16\n",
      "m.span(2) (6, 16)\n",
      "m.expand(r'\\2 \\1\\3'): wodeshijie hello!\n"
     ]
    }
   ],
   "source": [
    "import re\n",
    "m = re.match(r'(\\w+) (\\w+)(?P<sign>.*)', 'hello wodeshijie!')\n",
    "\n",
    "print \"m.string:\",m.string\n",
    "print \"m.re:\",m.re\n",
    "print \"m.pos\",m.pos\n",
    "print \"m.endpos:\",m.endpos\n",
    "print \"m.lastindex:\",m.lastindex\n",
    "print \"m.lastgroup:\",m.lastgroup\n",
    "\n",
    "print \"m.group(1,2):\",m.group(1,2)\n",
    "print \"m.groups():\",m.groups()\n",
    "print \"m.groupdict():\",m.groupdict()\n",
    "print \"m.start(2):\",m.start(2)\n",
    "print \"m.end(2):\",m.end(2)\n",
    "print \"m.span(2)\",m.span(2)\n",
    "print r\"m.expand(r'\\2 \\1\\3'):\", m.expand(r'\\2 \\1\\3')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Pattern"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Pattern对象是一个编译好的正则表达式，通过Pattern提供的一系列方法可以对文本进行匹配查找。<br>\n",
    "Pattern不能直接实例化，必须使用re.compile()进行构造。<br>\n",
    "Pattern提供了几个可读属性用于获取表达式的相关信息：<br>\n",
    "pattern: 编译时用的表达式字符串。<br>\n",
    "<br>\n",
    "flags: 编译时用的匹配模式。数字形式。<br>\n",
    "groups: 表达式中分组的数量。<br>\n",
    "groupindex: 以表达式中有别名的组的别名为键、以该组对应的编号为值的字典，没有别名的组不包含在内。<br>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "p.pattern: (\\w+) (\\w+)(?P<sign>.*)\n",
      "p.flags: 16\n",
      "p.groups 3\n",
      "p.groupindex {'sign': 3}\n"
     ]
    }
   ],
   "source": [
    "import re\n",
    "p = re.compile(r'(\\w+) (\\w+)(?P<sign>.*)',re.DOTALL)\n",
    "\n",
    "print \"p.pattern:\",p.pattern\n",
    "print \"p.flags:\",p.flags\n",
    "print \"p.groups\",p.groups\n",
    "print \"p.groupindex\",p.groupindex"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 使用pattern"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "** match(string[, pos[, endpos]]) | re.match(pattern, string[, flags]): <br>\n",
    "这个方法将从string的pos下标处起尝试匹配pattern:<br> **\n",
    "\n",
    "如果pattern结束时仍可匹配，则返回一个Match对象<br>\n",
    "\n",
    "如果匹配过程中pattern无法匹配，或者匹配未结束就已到达endpos，则返回None。<br>\n",
    "\n",
    "pos和endpos的默认值分别为0和len(string)。 <br>\n",
    "\n",
    "** 注意：这个方法并不是完全匹配。当pattern结束时若string还有剩余字符，仍然视为成功。想要完全匹配，可以在表达式末尾加上边界匹配符'$'。**<br>\n",
    "\n",
    "** search(string[, pos[, endpos]]) | re.search(pattern, string[, flags]): <br> **\n",
    "\n",
    "** 这个方法从string的pos下标处起尝试匹配pattern<br> **\n",
    "\n",
    "如果pattern结束时仍可匹配，则返回一个Match对象<br>\n",
    "\n",
    "若无法匹配，则将pos加1后重新尝试匹配，直到pos=endpos时仍无法匹配则返回None。<br>\n",
    "\n",
    "pos和endpos的默认值分别为0和len(string))<br>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hwodeshijieg\n"
     ]
    }
   ],
   "source": [
    "# encoding: UTF-8\n",
    "import re\n",
    "\n",
    "# 将正则表达式编译成Pattern对象\n",
    "pattern = re.compile(r'H.*g')\n",
    "\n",
    "# 使用search()查找匹配的子串，不存在能匹配的子串时将返回None \n",
    "# 这个例子中使用match()无法成功匹配 \n",
    "match = pattern.search('hello Hwodeshijieg!')\n",
    "\n",
    "if match:\n",
    "    # 使用Match获得分组信息 \n",
    "    print match.group()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]):<br>\n",
    "按照能够匹配的子串将string分割后返回列表。<br>\n",
    "maxsplit用于指定最大分割次数，不指定将全部分割。<br>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['one', 'two', 'three', 'four', '']\n"
     ]
    }
   ],
   "source": [
    "import re\n",
    "\n",
    "p = re.compile(r'\\d+')\n",
    "print p.split('one1two2three3four4')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]):<br>\n",
    "搜索string，以列表形式返回全部能匹配的子串。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['1', '2', '3', '4']\n"
     ]
    }
   ],
   "source": [
    "import re\n",
    "\n",
    "p = re.compile(r'\\d+')\n",
    "print p.findall('one1two2three3four4')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags]):<br>\n",
    "搜索string，返回一个顺序访问每一个匹配结果（Match对象）的迭代器。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "2\n",
      "3\n",
      "4\n"
     ]
    }
   ],
   "source": [
    "import re\n",
    "\n",
    "p = re.compile(r'\\d+')\n",
    "for m in p.finditer('one1two2three3four4'):\n",
    "    print m.group()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "sub(repl, string[, count]) | re.sub(pattern, repl, string[, count]): 使用repl替换string中每一个匹配的子串后返回替换后的字符串。 当repl是一个字符串时，可以使用\\id或\\g、\\g引用分组，但不能使用编号0。 当repl是一个方法时，这个方法应当只接受一个参数（Match对象），并返回一个字符串用于替换（返回的字符串中不能再引用分组）。 count用于指定最多替换次数，不指定时全部替换。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "say i,wodeshijie hello!\n",
      "I Say,Hello Wodeshijie!\n"
     ]
    }
   ],
   "source": [
    "import re\n",
    "\n",
    "p = re.compile(r'(\\w+) (\\w+)')\n",
    "s = 'i say,hello wodeshijie!'\n",
    "\n",
    "print p.sub(r'\\2 \\1', s)\n",
    "\n",
    "def func(m):\n",
    "    return m.group(1).title() + ' ' + m.group(2).title()\n",
    "\n",
    "print p.sub(func, s)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "sub(repl, string[, count]) | re.sub(pattern, repl, string[, count]): 使用repl替换string中每一个匹配的子串后返回替换后的字符串。 当repl是一个字符串时，可以使用\\id或\\g、\\g引用分组，但不能使用编号0。 当repl是一个方法时，这个方法应当只接受一个参数（Match对象），并返回一个字符串用于替换（返回的字符串中不能再引用分组）。 count用于指定最多替换次数，不指定时全部替换。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('say i, wodeshijie hello!', 2)\n",
      "('I Say, Hello Wodeshijie!', 2)\n"
     ]
    }
   ],
   "source": [
    "import re\n",
    "\n",
    "p = re.compile(r'(\\w+) (\\w+)')\n",
    "s = 'i say, hello wodeshijie!'\n",
    "\n",
    "print p.subn(r'\\2 \\1', s)\n",
    "\n",
    "def func(m):\n",
    "    return m.group(1).title() + ' ' + m.group(2).title()\n",
    "\n",
    "print p.subn(func, s)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.15"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
